package cn.xtits.sync.sdk.producer;

import cn.xtits.xtf.common.db.DbConn;
import cn.xtits.xtf.common.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class Producer {

    private static String dbUrl;
    private static String driverClassName;
    private static String dbusername;
    private static String dbpassword;


    @Value("${xtf.datasource.url}")
    public void setDbUrl(String dbUrl) {
        Producer.dbUrl = dbUrl;
    }

    @Value("${xtf.datasource.driver-class-name}")
    public void setDriverClassName(String driverClassName) {
        Producer.driverClassName = driverClassName;
    }

    @Value("${xtf.datasource.username}")
    public void setDbusername(String dbusername) {
        Producer.dbusername = dbusername;
    }

    @Value("${xtf.datasource.password}")
    public void setDbpassword(String dbpassword) {
        Producer.dbpassword = dbpassword;
    }

    private static int count = 1;

    private static String insertSql = "insert into sc_synccommand(Sourcekey,SourceTable,UpdateTable,UpdateInstance,ConnStr,FinishFlag) values ({0});";

    private static String listSql = "select * from sc_tablemapping where SourceTable=''{0}'' and DeleteFlag=0";

    public static DbConn getConn() throws Exception {
        String connStr = MessageFormat.format("url={0}|username={1}|password={2}|driverClassName={3}|maxWait=5000", dbUrl, dbusername, dbpassword, driverClassName);
        DbConn conn = DbConn.createConn(connStr);
        return conn;
    }

    public static DbConn getConn(String connStr) throws Exception {
        DbConn conn = DbConn.createConn(connStr);
        return conn;
    }

    private static List<String> getMatchers(String regex, String source) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        List<String> list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list;
    }

    public static List<Map<String, Object>> Do(String table, Object object) {
        try (DbConn conn = getConn()) {
            String sql = MessageFormat.format(listSql, table);
            List<Map<String, Object>> list = conn.executeList(sql);

            for (Map<String, Object> item : list) {

                //获取更新
                String updateTemlate = item.get("UpdateTemlate").toString();
                List<String> matchers = getMatchers("\\[\\w*]", updateTemlate);
                for (String matcher : matchers) {
                    Object value = BeanUtil.getValue(object, matcher.substring(1, matcher.length() - 1));
                    updateTemlate = updateTemlate.replace(matcher, "''" + value + "''");
                }
                //更新 Sourcekey,SourceTable,UpdateTable,UpdateInstance,ConnStr,FinishFlag

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("'" + BeanUtil.getValue(object, "id") + "',");//Sourcekey
                stringBuilder.append("'" + table + "',");//SourceTable
                stringBuilder.append("'" + item.get("UpdateTable").toString() + "',");//SourceTable
                stringBuilder.append("'" + updateTemlate + "',");//UpdateInstance
                stringBuilder.append("'" + item.get("ConnStr").toString() + "',");//ConnStr
                stringBuilder.append(0);//ConnStr
                String executeSql = MessageFormat.format(insertSql, stringBuilder.toString());
                conn.executeNonQuery(executeSql);
            }
            return list;

        } catch (Exception e) {
            System.err.println("添加异常..." + e.getMessage());
            return null;
        }
    }
}
